#include "init.h"

cr_state *init(int max_w, int max_h, char *font, int font_size) {
    cr_state *state = malloc(sizeof(cr_state));
    /* bool */
    state->render_change = false;
    state->incomplete_parse = false;
    /* int */
    state->frame = 0;
    state->window_w = max_w;
    state->window_h = max_h;
    state->font_height = 0;
    state->border = (max_w + max_h) * 0.034;
    /* uint64_t */
    state->previous_info_hash = 0;
    /* cr_button_node */
    state->root = NULL;
    state->tail = NULL;
    /* cr_track */
    state->track = NULL;
    /* cr_player */
    state->player = NULL;
    /* drawable */
    for (int i = 0; i < TOKEN_ENUM_SIZE; i++) {
        state->update[i] = false;
        state->drawables[i].texture = NULL;
        state->drawextras[i].texture = NULL;
    }

    /* try to init SDL_ttf */
    if (TTF_Init() == -1) {
        fprintf(stderr, "error: TTF_Init error: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    /* init rest of components */
    init_input();
    init_graphics(state, font, max_w, max_h, font_size);
    init_cmus_rg(&state->font, &state->render_change, &state->track, &state->player, &state->frame);

    return state;
}

/* post game cleanup */
void cleanup() {
    cleanup_cmus_rg(state->track, state->player);
    cleanup_graphics(&state->window, &state->renderer, &state->font);
    cleanup_input(state->root);
    TTF_Quit();
    SDL_Quit();

    /* at last */
    free(state);
}
